//
//  ViewController.m
//  RequestCache
//
//  Created by Hunk on 12-1-31.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "ViewController.h"

@implementation ViewController
@synthesize urlConnection;

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button setFrame:CGRectMake(100.0, 100.0, 100.0, 35.0)];
    [button setTitle:@"BUTTON" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(buttonHandle:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
}

- (void)buttonHandle:(id)sender
{
    NSString *testURLString = @"http://www.360buy.com";
    
    if([testURLString length] == 0)
    {
        NSLog(@"Nil or empty url given\n");
        
        return;
    }
    
    // URL cache
    NSURLCache *urlCache = [NSURLCache sharedURLCache];
    
    // 设置缓存大小为1M
    [urlCache setMemoryCapacity:1 * 1024 * 1024];
    
    // Create url
    NSURL *url = [NSURL URLWithString:testURLString];
    
    // Create request
    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url
                                                              cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                          timeoutInterval:60.0f];
    // 从请求中获取缓存输出
    NSCachedURLResponse *cacheURLResponse = [urlCache cachedResponseForRequest:urlRequest];
    
    // 判断是否有缓存
    if(cacheURLResponse != nil)
    {
        NSLog(@"如果有缓存输出，从缓存中获取数据");
        
        [urlRequest setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
    }
    
    self.urlConnection = nil;
    
    NSURLConnection *newConnection = [[NSURLConnection alloc] initWithRequest:urlRequest
                                                                     delegate:self
                                                             startImmediately:YES];
    
    self.urlConnection = newConnection;
    
    [newConnection release];
}

#pragma mark -
#pragma mark NSURLConnectionDelegate methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"将接收输出\n");
}

- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response
{
    NSLog(@"即将发送请求\n");    
    
    return(request);
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{   
    NSLog(@"接收数据, 数据长度为 = %lu\n", (unsigned long)[data length]);
}

- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse
{
    NSLog(@"将缓存输出\n");    
    
    return(cachedResponse);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"请求完成\n");
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"请求失败\n");
}   

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

@end
